package com.yanghui.dtracing.reporter.zipkin;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import zipkin2.Call;
import zipkin2.codec.Encoding;
import zipkin2.reporter.BytesMessageEncoder;
import zipkin2.reporter.Sender;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class ZipkinRestTemplateSender extends Sender {

    private OkHttpClient okHttpClient;

    private String url;

    public ZipkinRestTemplateSender(String baseUrl){
        this.url = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "api/v2/spans";
        this.okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    @Override
    public Encoding encoding() {
        return Encoding.JSON;
    }

    @Override
    public int messageMaxBytes() {
        // Max span size is 2MB
        return 2 * 1024 * 1024;
    }

    @Override
    public int messageSizeInBytes(List<byte[]> encodedSpans) {
        return encoding().listSizeInBytes(encodedSpans);
    }

    @Override
    public Call<Void> sendSpans(List<byte[]> encodedSpans) {
        try {
            byte[] message = BytesMessageEncoder.JSON.encode(encodedSpans);
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),message);
            Request request = new Request.Builder()
                    .url(this.url)
                    .post(requestBody)
                    .build();
            okhttp3.Call call = this.okHttpClient.newCall(request);
            call.execute();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return Call.create(null);
    }
}
